package init

import (
	"fmt"
	"log"
	"user-srv/basic/global"
	"user-srv/handler/model"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func Mysql() {
	var err error
	data := global.Config.Mysql

	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local", data.User, data.Password, data.Host, data.Port, data.DataBases)
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("连接失败")
	} else {
		fmt.Printf("数据库连接成功")
	}

	err = global.DB.AutoMigrate(&model.User{}, &model.Address{}, &model.Admin{}, &model.Delivery{},
		&model.Evaluation{}, &model.Favorite{}, &model.Good{}, &model.Order{})

	err = global.DB.AutoMigrate(&model.DeliveryMessage{}, &model.AdminMessage{}, &model.Address{}, &model.Admin{}, &model.Delivery{}, &model.Evaluation{}, &model.Favorite{}, &model.Good{}, &model.Class{}, &model.Order{}, &model.User{})

	if err != nil {
		panic(err)
	}
	log.Println("数据表迁移成功")

}
